package wechat

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/fbbi/go-wechat/util"
)

const (
	WXAPITagGet             = `tags/get?access_token=%s`                    //获取标签列表
	WXAPITagAdd             = `tags/create?access_token=%s`                 // 创建标签
	WXAPITagDel             = `tags/delete?access_token=%s`                 // 删除标签
	WXAPIbatchCanceUserlTag = `tags/members/batchuntagging?access_token=%s` //批量取消标签
	WXAPIbatchAddUserTag    = `tags/members/batchtagging?access_token=%s`   //批量打标签
)

type MpTag struct {
	Id    int    `json:"id"`
	Name  string `json:"name"`  //标签名，UTF8编码
	Count int    `json:"count"` //标签下粉丝数
}

type MpTagListResp struct {
	WxErr
	TagList []MpTag `json:"tags"`
}
type MpTagResp struct {
	WxErr
	MpTag MpTag `json:"tag"`
}

// 获取标签列表
func (s *Server) GetMpTagList() (tagList []MpTag, err error) {
	var resp MpTagListResp
	url := fmt.Sprintf(s.RootUrl+WXAPITagGet, s.GetAccessToken())
	req := map[string]interface{}{}
	var response []byte
	response, err = util.PostJson(url, req)
	if err != nil {
		return
	}
	if err = json.Unmarshal(response, &resp); err != nil {
		return
	}
	tagList = resp.TagList
	return
}

// 新增标签
func (s *Server) CreateMpTag(tagName string) (tag MpTag, err error) {
	var resp MpTagResp
	url := fmt.Sprintf(s.RootUrl+WXAPITagAdd, s.GetAccessToken())
	req := map[string]interface{}{
		"tag": map[string]interface{}{
			"name": tagName,
		},
	}
	var response []byte
	response, err = util.PostJson(url, req)
	if err != nil {
		return
	}
	if err = json.Unmarshal(response, &resp); err != nil {
		return
	}
	tag = resp.MpTag
	return
}

// 删除标签
func (s *Server) DelMpTag(TagId int) (err error) {
	var resp WxErr
	url := fmt.Sprintf(s.RootUrl+WXAPITagDel, s.GetAccessToken())
	req := map[string]interface{}{
		"tag": map[string]interface{}{
			"id": TagId,
		},
	}
	var response []byte
	response, err = util.PostJson(url, req)
	if err != nil {
		err = errors.New(resp.ErrMsg)
		return
	}
	if err = json.Unmarshal(response, &resp); err != nil {
		err = errors.New(resp.ErrMsg)
		return
	}
	return
}

// 批量取消标签
func (s *Server) BatchMpUnTagging(TagId int, OpenIdList []string) (err error) {
	var resp WxErr
	url := fmt.Sprintf(s.RootUrl+WXAPIbatchCanceUserlTag, s.GetAccessToken())
	req := map[string]interface{}{
		"openid_list": OpenIdList,
		"tagid":       TagId,
	}
	var response []byte
	response, err = util.PostJson(url, req)
	if err != nil {
		err = errors.New(resp.ErrMsg)
		return
	}
	if err = json.Unmarshal(response, &resp); err != nil {
		err = errors.New(resp.ErrMsg)
		return
	}
	return
}

// 批量打标签
func (s *Server) BatchMpTagging(TagId int, OpenIdList []string) (err error) {
	var resp WxErr
	url := fmt.Sprintf(s.RootUrl+WXAPIbatchAddUserTag, s.GetAccessToken())
	req := map[string]interface{}{
		"openid_list": OpenIdList,
		"tagid":       TagId,
	}
	var response []byte
	response, err = util.PostJson(url, req)
	if err != nil {
		return
	}
	if err = json.Unmarshal(response, &resp); err != nil {
		return
	}
	return
}
